<?php

namespace App\Http\Controllers\Attendance;

use App\Http\Controllers\Controller;
use App\Imports\Attendance\AttendanceImport;
use App\Models\Attendance\Machine;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class MachineController extends Controller
{
    public function machineList(Request $request)
    {
        $params = $request->all();
        $actualSignTime = Machine::query()->groupBy('sign_time')->orderByDesc('sign_time')->first()->sign_time;
        $data = $this->getAttendanceList($params, $actualSignTime)
            ->orderBy('sign_time', 'desc')
            ->get()
            ->toArray();
        if ($data) {
            $data = $this->transData($data);
        }

        return response()->formatJson([
            'machineRecord' => $data, 'actualSignTime' => $actualSignTime,
        ]);
    }

    public function getAttendanceList($params, $actualSignTime)
    {
        $query = Machine::query();

        if (isset($params['date'])) {
            $date = date('Y-m-d', strtotime($params['date']));
        } else {
            $date = date('Y-m-d', strtotime($actualSignTime));
        }
        $query->whereDate('sign_time', $date);

        return $query;
    }

    public function transData($data)
    {
        $data = collect($data)->groupBy('name')->toArray();
        $postData = [];
        foreach ($data as $name => $driver) {
            $count = count($driver);
            $minDate = $this->searchMin($driver, 'sign_time');
            $minHour = date('H:i:s', strtotime($minDate));
            $maxDate = $this->searchMax($driver, 'sign_time');
            $maxHour = date('H:i:s', strtotime($maxDate));
            $workHour = number_format((strtotime($maxDate) - strtotime($minDate)) % 86400 / 3600, 1);
            $postData[] = [
                'name'          => $name,
                'count'         => $count,
                'signRange'     => $minHour.' - '.$maxHour,
                'status'        => $count === 4 && $workHour > 0 ? '正常' : '异常',
                'workHour'      => $workHour,
                'normalTime'    => null,
                'overtime'      => null,
                'fixTime'       => null,
                'leaveTime'     => null,
                'stopTime'      => null,
                'nightOvertime' => null,
                'edit'          => false,
            ];
        }

        return $postData;
    }

    /**
     * 取二维数组的某一项的最大值或者最小值
     *
     * @param $arr
     * @param $field
     *
     * @return bool|mixed
     */
    public function searchMin($arr, $field) // 最小值 只需要最后一个max函数  替换为 min函数即可
    {
        if (! is_array($arr) || ! $field) { //判断是否是数组以及传过来的字段是否是空
            return false;
        }

        $temp = [];
        foreach ($arr as $key => $val) {
            $temp[] = $val[$field]; // 用一个空数组来承接字段
        }
        return min($temp);  // 用php自带函数 max 来返回该数组的最大值，一维数组可直接用max函数
    }

    /**
     * 取二维数组的某一项的最大值或者最小值
     *
     * @param $arr
     * @param $field
     *
     * @return bool|mixed
     */
    public function searchMax($arr, $field) // 最小值 只需要最后一个max函数  替换为 min函数即可
    {
        if (! is_array($arr) || ! $field) { //判断是否是数组以及传过来的字段是否是空
            return false;
        }

        $temp = [];
        foreach ($arr as $key => $val) {
            $temp[] = $val[$field]; // 用一个空数组来承接字段
        }
        return max($temp);  // 用php自带函数 max 来返回该数组的最大值，一维数组可直接用max函数
    }

    /**
     *  导入行政人员数据
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function importMachine(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $excelData = Excel::toArray(new AttendanceImport, public_path().$urlParse['path']);
        $fullData = $excelData[0];

        // 删除第一行
        array_shift($fullData);

        $fields = [
            'number',
            'work_number',
            'name',
            'department',
            'office',
            'sign_time',
            'week',
            'type',
            'remark',
        ];

        $data = [];
        foreach ($fullData as $row) {
            $item = [];
            foreach ($fields as $index => $field) {
                $item[$field] = $row[$index];
            }

            if ($item['name']) {
                // 删除姓名空格
                $item['name'] = trim(str_replace(' ', '', $item['name']));
            }
            $item['sign_time'] = $item['sign_time'] === '' ? null : $item['sign_time'];
            $item['created_at'] = date('Y-m-d H:i:s');

            $data[] = $item;
        }

        return response()->formatJson(Machine::query()->insert($data), '导入成功');
    }
}
